package com.aw.guiguzi.util

import android.content.Context
import android.os.Build
import android.os.Environment
import android.util.Log
import com.aw.baselib.util.AwDateUtil
import com.aw.baselib.util.AwSystemUtil
import com.aw.baselib.util.AwVersionUtil
import com.aw.guiguzi.base.MyApp
import com.aw.guiguzi.util.AppUserUtil.account
import com.aw.guiguzi.util.AppUserUtil.nickname
import java.io.File
import java.io.FileInputStream
import java.io.FileWriter
import java.net.HttpURLConnection
import java.net.URL
import java.text.DecimalFormat
import java.util.Date

/**
 * @author : hzw
 * @date : 2021/4/1
 */
object MyFileUtil {
    private var mContext: Context? = null
    const val SIZETYPE_B = 1
    const val SIZETYPE_KB = 2
    const val SIZETYPE_MB = 3
    const val SIZETYPE_GB = 4

    //    public static String filePath_log = Environment.getExternalStorageDirectory() + "/ZdBle.txt";
    var filePath_log = ""
    private val localFilePath: String
        private get() = if (Environment.getExternalStorageState() == "mounted") {
            Environment.getExternalStorageDirectory().toString()
        } else {
            Environment.getDownloadCacheDirectory().toString()
        }
    val allFileList: List<String>
        get() {
            val dateStr =
                AwDateUtil.formatDate(Date(System.currentTimeMillis()), AwDateUtil.FORMAT_YMD)
            val list: MutableList<String> = ArrayList()
            val file = File(mContext!!.getExternalFilesDir("")!!.absolutePath)
            val files = file.listFiles()
            for (i in files.indices) { // 遍历目录下所有的文件
                if (files[i].name.contains("_")) {
                    writeFile(
                        "{Local journal..." + files[i].name.split("_".toRegex())
                            .dropLastWhile { it.isEmpty() }
                            .toTypedArray()[0] + "}")
                }
                if (!files[i].name.contains(dateStr) && files[i].name.contains("_guessapp")) {
                    list.add(files[i].absolutePath)
                }
            }
            return list
        }
    val defaultInfoStr: String
        get() = "{手机版本: " + Build.VERSION.SDK_INT + "; 型号: " + AwSystemUtil.getSystemModel() + "; APP版本: " + AwVersionUtil.getVersion(
            MyApp.instance
        ) +
                "}"
    val defaultRoleStr: String
        get() = "角色: " + nickname
    val fileUrl: String
        get() {
            val dateStr =
                AwDateUtil.formatDate(Date(System.currentTimeMillis()), AwDateUtil.FORMAT_YMD)
            return mContext!!.getExternalFilesDir("")!!.absolutePath + "/" + dateStr + "_" + account + "_guessapp.txt"
        }

    fun writeDefault(isMain: Boolean) {
        writeFile(defaultInfoStr)
        if (isMain) {
            writeFile("Main." + defaultRoleStr)
        } else {
            writeFile(defaultRoleStr)
        }
    }

    fun setContext(context: Context?) {
        mContext = context
        filePath_log = fileUrl
    }

    fun writeFile(str: String) {
        var writer: FileWriter? = null
        try {
            val f = File(filePath_log)
            if (!f.exists()) {
                f.createNewFile()
                writeDefault(false)
            }
            val fileSize = getFileOrFilesSize(filePath_log, SIZETYPE_MB)
            if (fileSize > 10) {
                f.delete()
                f.createNewFile()
                writeDefault(false)
            }
            val dateStr = AwDateUtil.formatDate(Date(System.currentTimeMillis()), "HH:mm:ss")
            writer = FileWriter(f, true)
            writer.write("【$dateStr】 $str\n")
            writer.flush()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                writer!!.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun getFileOrFilesSize(filePath: String?, sizeType: Int): Double {
        val file = File(filePath)
        var blockSize: Long = 0
        try {
            blockSize = if (file.isDirectory) {
                getFileSizes(file)
            } else {
                getFileSize(file)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("获取文件大小", "获取失败!")
        }
        return FormetFileSize(blockSize, sizeType)
    }

    /**
     * 获取指定文件大小
     *
     * @throws Exception
     */
    @Throws(Exception::class)
    fun getFileSize(file: File): Long {
        var size: Long = 0
        if (file.exists()) {
            val fis = FileInputStream(file)
            size = fis.available().toLong()
        } else {
            file.createNewFile()
            Log.e("获取文件大小", "文件不存在!")
        }
        return size
    }

    /**
     * 获取下载 URL 的文件的大小
     */
    fun getFileSize(address: String?): Long {
        var filesize: Long = 0
        var urlConn: HttpURLConnection? = null
        try {
            val url = URL(address)
            urlConn = url.openConnection() as HttpURLConnection
            urlConn.connectTimeout = 10000
            urlConn!!.readTimeout = 10000
            urlConn.connect()
            filesize = urlConn.contentLength.toLong()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            urlConn!!.disconnect()
        }
        return filesize
    }

    /**
     * 获取指定文件夹(目录)大小
     *
     * @param f
     * @return
     * @throws Exception
     */
    @Throws(Exception::class)
    private fun getFileSizes(f: File): Long {
        var size: Long = 0
        val flist = f.listFiles()
        for (i in flist.indices) {
            size = if (flist[i].isDirectory) {
                size + getFileSizes(flist[i])
            } else {
                size + getFileSize(flist[i])
            }
        }
        return size
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    private fun FormetFileSize(fileS: Long): String {
        val df = DecimalFormat("#.00")
        var fileSizeString = ""
        val wrongSize = "0B"
        if (fileS == 0L) {
            return wrongSize
        }
        fileSizeString = if (fileS < 1024) {
            df.format(fileS.toDouble()) + "B"
        } else if (fileS < 1048576) {
            df.format(fileS.toDouble() / 1024) + "KB"
        } else if (fileS < 1073741824) {
            df.format(fileS.toDouble() / 1048576) + "MB"
        } else {
            df.format(fileS.toDouble() / 1073741824) + "GB"
        }
        return fileSizeString
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    private fun FormetFileSize(fileS: Long, sizeType: Int): Double {
        val df = DecimalFormat("#.00")
        var fileSizeLong = 0.0
        when (sizeType) {
            SIZETYPE_B -> fileSizeLong = java.lang.Double.valueOf(df.format(fileS.toDouble()))
            SIZETYPE_KB -> fileSizeLong =
                java.lang.Double.valueOf(df.format(fileS.toDouble() / 1024))

            SIZETYPE_MB -> fileSizeLong =
                java.lang.Double.valueOf(df.format(fileS.toDouble() / 1048576))

            SIZETYPE_GB -> fileSizeLong = java.lang.Double.valueOf(
                df
                    .format(fileS.toDouble() / 1073741824)
            )

            else -> {}
        }
        return fileSizeLong
    }
}